//
//  SlideSwitchView.m
//  SlideView
//
//  Created by zhaojh on 5/7/14.
//  Copyright (c) 2014年 zjh. All rights reserved.
//

#import "SlideSwitchView.h"
#import "PullDownView.h"

#define kHeightOfTopScrollView 44
#define kWidthOfButtonMargin   0
#define kFontSizeOfTabButton   16
#define kTagOfRightSideButton  1000
#define kTagOfTabButtonInit    2000
#define kTagOfPullViewInit     3000

#define BOUNDS_WIDTH   (self.bounds.size.width)
#define BOUNDS_HEIGHT  (self.bounds.size.height)

@implementation TopScrollView

//- (void)drawRect:(CGRect)rect
//{
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
//    CGContextSetLineWidth(context, 0.2);
//    CGContextMoveToPoint(context, 320, self.frame.size.height-0.2);
//    CGContextAddLineToPoint(context, 0, self.frame.size.height-0.2);
//    CGContextStrokePath(context);
//}

@end

@interface SlideSwitchView () <PullDownViewDelegate>
{
    CGFloat _rootScrollViewContentOffsetX;
    NSInteger _tabButtonTag;
    UIImageView *_shadowImageView;
    BOOL _isLeftScroll;     //是否左滑动
    BOOL _isRootScroll;     //是否主视图滑动
    BOOL _isBuildUI;
}

@end

@implementation SlideSwitchView

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initValues];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initValues];
    }
    return self;
}

- (void)initValues
{
    _isBuildUI = NO;
    _rootScrollViewContentOffsetX = 0.0f;
    _tabButtonTag = kTagOfTabButtonInit;
    self.tabItemNormalColor = [PullDownView colorFromHexRGB:@"ffb751"];
    self.tabItemSelectedColor = [UIColor whiteColor];
}

- (UIScrollView *)rootScrollView
{
    if (!_rootScrollView) {
        _rootScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kHeightOfTopScrollView, BOUNDS_WIDTH, BOUNDS_HEIGHT-kHeightOfTopScrollView)];
        _rootScrollView.delegate = self;
        _rootScrollView.pagingEnabled = YES;
        _rootScrollView.userInteractionEnabled = YES;
        _rootScrollView.bounces = NO;
        _rootScrollView.showsHorizontalScrollIndicator = NO;
        _rootScrollView.showsVerticalScrollIndicator = NO;
        _rootScrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
        [_rootScrollView.panGestureRecognizer addTarget:self action:@selector(rootScrollViewHandlePan:)];
        [self addSubview:_rootScrollView];
    }
    return _rootScrollView;
}

- (TopScrollView *)topScrollView
{
    if (!_topScrollView) {
        _topScrollView = [[TopScrollView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS_WIDTH, kHeightOfTopScrollView)];
        _topScrollView.delegate = self;
        _topScrollView.backgroundColor = [UIColor clearColor];
        _topScrollView.pagingEnabled = NO;
        _topScrollView.showsHorizontalScrollIndicator = NO;
        _topScrollView.showsVerticalScrollIndicator = NO;
        _topScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [self addSubview:_topScrollView];
    }
    return _topScrollView;
}

- (NSMutableArray *)viewArray
{
    if (!_viewArray) {
        _viewArray = [[NSMutableArray alloc] init];
    }
    return _viewArray;
}

- (void)setRightButton:(UIButton *)rightButton
{
    UIButton *button = (UIButton *)[self viewWithTag:kTagOfRightSideButton];
    if (button) {
        [button removeFromSuperview];
    }
    rightButton.tag = kTagOfRightSideButton;
    _rightButton = rightButton;
    [self addSubview:_rightButton];
}

#pragma mark -
#pragma mark 开始加载UI

//调整布局
- (void)layoutSubviews
{
    if (!_isBuildUI) {
        [self startBuildUI];
    }
    //如果有设置右侧视图，缩小顶部滚动视图的宽度以适应按钮
    if (self.rightButton.bounds.size.width > 0) {
        self.rightButton.frame = CGRectMake(self.bounds.size.width - self.rightButton.bounds.size.width, 0,
                                            self.rightButton.bounds.size.width, self.topScrollView.bounds.size.height);
        
        self.topScrollView.frame = CGRectMake(0, 0,BOUNDS_WIDTH-self.rightButton.bounds.size.width, kHeightOfTopScrollView);
    }
    
    //更新主视图的总宽度
    self.rootScrollView.contentSize = CGSizeMake(self.bounds.size.width * [self.viewArray count], 0);
    
    //更新主视图各个子视图的宽度
    for (int i = 0; i < [self.viewArray count]; i++) {
        UIViewController *listVC = self.viewArray[i];
        listVC.view.frame = CGRectMake(0+self.rootScrollView.bounds.size.width*i, 0,
                                       self.rootScrollView.bounds.size.width, self.rootScrollView.bounds.size.height);
    }
    
    //滚动到选中的视图
    [self.rootScrollView setContentOffset:CGPointMake((_tabButtonTag - kTagOfTabButtonInit)*BOUNDS_WIDTH, 0) animated:NO];
    
    //调整顶部滚动视图选中按钮位置
    UIButton *button = (UIButton *)[self.topScrollView viewWithTag:_tabButtonTag];
    [self adjustTopScrollViewContentX:button];
}

- (void)startBuildUI
{
    NSAssert(self.dataSource != nil, @"dataSource no-nil");
    NSAssert(self.delegate != nil, @"delegate no-nil");
    NSUInteger number = [self.dataSource numberOfTabs];
    for (int i=0; i<number; i++) {
        UIViewController *vc = [self.dataSource slideSwitchViewOfTab:i];
        [self.viewArray addObject:vc];
        [self.rootScrollView addSubview:vc.view];
    }
    
    [self buildSlideButtons];
    
    //选中第一个view
    if (self.delegate && [self.delegate respondsToSelector:@selector(slideSwitchView:didSelectTab:)]) {
        [self.delegate slideSwitchView:self didSelectTab:_tabButtonTag - kTagOfTabButtonInit];
    }
    
    _isBuildUI = YES;
}

- (void)buildSlideButtons
{
    _shadowImageView = [[UIImageView alloc] init];
    [_shadowImageView setImage:self.shadowImage];
    [self.topScrollView addSubview:_shadowImageView];
    
    CGFloat topScrollViewContentWidth = kWidthOfButtonMargin;
    CGFloat xOffset = kWidthOfButtonMargin;
    for (int i=0; i<self.viewArray.count; i++) {
        UIViewController *vc = self.viewArray[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        CGSize textSize = [vc.title sizeWithFont:[UIFont systemFontOfSize:kFontSizeOfTabButton]
//                               constrainedToSize:CGSizeMake(self.topScrollView.bounds.size.width, kHeightOfTopScrollView)
//                                   lineBreakMode:NSLineBreakByTruncatingTail];
        //累计每个tab文字的长度
        float everWidth = self.topScrollView.frame.size.width/3.0;
        topScrollViewContentWidth += kWidthOfButtonMargin+everWidth;
        //设置按钮尺寸
        [button setFrame:CGRectMake(xOffset, 0, everWidth, kHeightOfTopScrollView)];
        //计算下一个tab的x偏移量
        xOffset += everWidth + kWidthOfButtonMargin;
        button.tag = i + kTagOfTabButtonInit;
        if (i == 0) {
            _shadowImageView.frame = CGRectMake(kWidthOfButtonMargin, 0, everWidth, _shadowImage.size.height);
            button.selected = YES;
        }
//        [button setImage:[UIImage imageNamed:@"buttonline.png"] forState:UIControlStateNormal];
//        [button setImage:[UIImage imageNamed:@"buttonline.png"] forState:UIControlStateSelected];
//        button.imageEdgeInsets = UIEdgeInsetsMake ( 35 ,  5 , 2 , 5 );
        [button setTitle:vc.title forState:UIControlStateNormal];
        button.backgroundColor = [UIColor colorWithRed:236/255.0f green:235/255.0f blue:243/255.0f alpha:1];
        button.titleLabel.font = [UIFont systemFontOfSize:kFontSizeOfTabButton];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [button setTitleColor:BASIC_BLUE_COLOR forState:UIControlStateSelected];
        if (self.isShowPullView) [self backGroudImageWithButton:button isUp:NO];
        else [self backGroudImageWithButton:button];
        [button addTarget:self action:@selector(selectTopButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.topScrollView addSubview:button];
        
        if (self.isShowPullView) {
            NSAssert(self.dataSource != nil, @"dataSource no-nil");
            NSArray *items = [self.dataSource pullDownItemsAtIndex:i];
            PullDownView *pullView = [[PullDownView alloc] initWithFrame:CGRectMake(7.5, 0, 0, 0)
                                                               withItems:items];
            pullView.hidden = YES;
            pullView.tag = i + kTagOfPullViewInit;
            pullView.delegate = self;
            [self addSubview:pullView];
        }
    }
    //设置顶部滚动视图的内容总尺寸
    self.topScrollView.contentSize = CGSizeMake(topScrollViewContentWidth, kHeightOfTopScrollView);
}

- (void)backGroudImageWithButton:(UIButton *)button isUp:(BOOL)isUp
{
    NSInteger tag = button.tag - kTagOfTabButtonInit;
    switch (tag) {
        case 0:
            if (isUp) {
                [button setBackgroundImage:[UIImage imageNamed:@"left_up_n"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"left_up_h"] forState:UIControlStateSelected];
            } else {
                [button setBackgroundImage:[UIImage imageNamed:@"left_down_n"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"left_down_h"] forState:UIControlStateSelected];
            }
            break;
        case 1:
            if (isUp) {
                [button setBackgroundImage:[UIImage imageNamed:@"middle_up_n"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"middle_up_h"] forState:UIControlStateSelected];
            } else {
                [button setBackgroundImage:[UIImage imageNamed:@"middle_down_n"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"middle_down_h"] forState:UIControlStateSelected];
            }
            break;
        case 2:
            if (isUp) {
                [button setBackgroundImage:[UIImage imageNamed:@"right_up_n"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"right_up_h"] forState:UIControlStateSelected];
            } else {
                [button setBackgroundImage:[UIImage imageNamed:@"right_down_n"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"right_down_h"] forState:UIControlStateSelected];
            }
            
            break;
        default:
            break;
    }
}

- (void)backGroudImageWithButton:(UIButton *)button
{
    NSInteger tag = button.tag - kTagOfTabButtonInit;
    switch (tag) {
        case 0:
            
            [button setBackgroundImage:[UIImage imageNamed:@"message_left_n"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"message_left_h"] forState:UIControlStateSelected];
            break;
        case 1:
            [button setBackgroundImage:[UIImage imageNamed:@"message_middle_n"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"message_middle_h"] forState:UIControlStateSelected];
            break;
        case 2:
            [button setBackgroundImage:[UIImage imageNamed:@"message_right_n"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"message_right_h"] forState:UIControlStateSelected];
            break;
        default:
            break;
    }
    
}

- (void)showPullDownView:(NSInteger)index isSameView:(BOOL)isSame
{
    BOOL isChangePull = NO;
    if (!isSame) {
        for (int i=0; i<self.viewArray.count; i++) {
            PullDownView *pullView = (PullDownView *)[self viewWithTag:i+kTagOfPullViewInit];
            if (pullView.isShow) {
                isChangePull = YES;
                isSame = YES;
                break;
            }
        }
    }
    else {
        isChangePull = YES;
    }
    
    for (int i=0; i<self.viewArray.count; i++) {
        PullDownView *pullView = (PullDownView *)[self viewWithTag:i+kTagOfPullViewInit];
        if (index == i && isSame && isChangePull) {
            if (!pullView.isShow) {
                [self showPullView:pullView withIndex:i];
            } else {
                [self hiddenPullView:pullView withIndex:i];
            }
        }
        else {
            if (pullView.isShow) {
                [self hiddenPullView:pullView withIndex:i];
            }
        }
    }
}

- (void)showPullView:(PullDownView *)pullView withIndex:(NSInteger)index
{
    float height = 36.0f;
    CGRect frame = CGRectMake(7.5, self.topScrollView.frame.origin.y+self.topScrollView.frame.size.height, self.frame.size.width-15, height);
    pullView.isShow = YES;
    [UIView animateWithDuration:0.25 animations:^{
        CGRect rootFrame = self.rootScrollView.frame;
        rootFrame.origin.y += height;
        rootFrame.size.height -= height;
        self.rootScrollView.frame = rootFrame;
        pullView.frame = frame;
        pullView.index = index;
        pullView.hidden = NO;
        if (self.isShowPullView) [self backGroudImageWithButton:(UIButton *)[self viewWithTag:index+kTagOfTabButtonInit] isUp:YES];
        else [self backGroudImageWithButton:(UIButton *)[self viewWithTag:index+kTagOfTabButtonInit]];
    }];
}

- (void)hiddenPullView:(PullDownView *)pullView withIndex:(NSInteger)index
{
    float height = 36.0f;
    pullView.isShow = NO;
    [UIView animateWithDuration:0.25 animations:^{
        CGRect rootFrame = self.rootScrollView.frame;
        rootFrame.origin.y -= height;
        rootFrame.size.height += height;
        self.rootScrollView.frame = rootFrame;
        pullView.frame = CGRectMake(7.5, 0, 0, 0);
        pullView.hidden = YES;
        if (self.isShowPullView) [self backGroudImageWithButton:(UIButton *)[self viewWithTag:index+kTagOfTabButtonInit] isUp:NO];
        else [self backGroudImageWithButton:(UIButton *)[self viewWithTag:index+kTagOfTabButtonInit]];
    }];
}

- (void)selectTopButton:(UIButton *)sender
{
    //如果点击的tab文字显示不全，调整滚动视图x坐标使用使tab文字显示全
    [self adjustTopScrollViewContentX:sender];
    
    //如果更换按钮
    if (sender.tag != _tabButtonTag) {
        //取之前的按钮
        UIButton *lastButton = (UIButton *)[self.topScrollView viewWithTag:_tabButtonTag];
        lastButton.selected = NO;
        //赋值按钮ID
        _tabButtonTag = sender.tag;
        if (self.isShowPullView)
            [self showPullDownView:_tabButtonTag-kTagOfTabButtonInit isSameView:NO];
    } else {
        if (self.isShowPullView)
            [self showPullDownView:_tabButtonTag-kTagOfTabButtonInit isSameView:YES];
    }
    //按钮选中状态
    if (!sender.selected) {
        sender.selected = YES;
        [UIView animateWithDuration:0.1 animations:^{
            [_shadowImageView setFrame:CGRectMake(sender.frame.origin.x, 0, sender.frame.size.width, self.shadowImage.size.height)];
            
        } completion:^(BOOL finished) {
            if (finished) {
                //设置新页出现
                if (!_isRootScroll) {
                    [self.rootScrollView setContentOffset:CGPointMake((sender.tag-kTagOfTabButtonInit)*BOUNDS_WIDTH, 0) animated:NO];
                }
                _isRootScroll = NO;
                
                if (self.delegate && [self.delegate respondsToSelector:@selector(slideSwitchView:didSelectTab:)]) {
                    [self.delegate slideSwitchView:self didSelectTab:_tabButtonTag - kTagOfTabButtonInit];
                }
            }
        }];
    }
}

- (void)adjustTopScrollViewContentX:(UIButton *)sender
{
    //如果 当前显示的最后一个tab文字超出右边界
    if (sender.frame.origin.x - _topScrollView.contentOffset.x > BOUNDS_WIDTH - (kWidthOfButtonMargin+sender.bounds.size.width)) {
        //向左滚动视图，显示完整tab文字
        [_topScrollView setContentOffset:CGPointMake(sender.frame.origin.x - (_topScrollView.bounds.size.width- (kWidthOfButtonMargin+sender.bounds.size.width)), 0)  animated:YES];
    }
    
    //如果 （tab的文字坐标 - 当前滚动视图左边界所在整个视图的x坐标） < 按钮的隔间 ，代表tab文字已超出边界
    if (sender.frame.origin.x - _topScrollView.contentOffset.x < kWidthOfButtonMargin) {
        //向右滚动视图（tab文字的x坐标 - 按钮间隔 = 新的滚动视图左边界在整个视图的x坐标），使文字显示完整
        [_topScrollView setContentOffset:CGPointMake(sender.frame.origin.x - kWidthOfButtonMargin, 0)  animated:YES];
    }
}

-(void)rootScrollViewHandlePan:(UIPanGestureRecognizer*) panParam
{
    //当滑道左边界时，传递滑动事件给代理
    if(self.rootScrollView.contentOffset.x <= 0) {
        if (self.delegate
            && [self.delegate respondsToSelector:@selector(slideSwitchView:panLeftEdge:)]) {
            [self.delegate slideSwitchView:self panLeftEdge:panParam];
        }
    } else if(self.rootScrollView.contentOffset.x >= self.rootScrollView.contentSize.width - self.rootScrollView.bounds.size.width) {//当滑道右边界时，传递滑动事件给代理
        if (self.delegate
            && [self.delegate respondsToSelector:@selector(slideSwitchView:panRightEdge:)]) {
            [self.delegate slideSwitchView:self panRightEdge:panParam];
        }
    }
}

#pragma mark - 
#pragma mark PullDownViewDelegate
- (void)chooseButtonItem:(NSInteger)index
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectPullDownButton:)]) {
        [self.delegate selectPullDownButton:index];
    }
}

#pragma mark -
#pragma mark UIScrollViewDelegate
//滚动视图开始时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == self.rootScrollView) {
        _rootScrollViewContentOffsetX = scrollView.contentOffset.x;
    }
}

//滚动视图结束
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.rootScrollView) {
        //判断用户是否左滚动还是右滚动
        if (_rootScrollViewContentOffsetX < scrollView.contentOffset.x) {
            _isLeftScroll = YES;
        }
        else {
            _isLeftScroll = NO;
        }
    }
}

//滚动视图释放滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.rootScrollView) {
        _isRootScroll = YES;
        //调整顶部滑条按钮状态
        int tag = (int)scrollView.contentOffset.x/self.bounds.size.width+kTagOfTabButtonInit;
        UIButton *button = (UIButton *)[self.topScrollView viewWithTag:tag];
        if (tag == _tabButtonTag) {
            return;
        }
        [self selectTopButton:button];
    }
}



@end
